package com.ssfeng.netty;

import lombok.SneakyThrows;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Description:
 * @Author: liyuhang
 * @CreateTime: 2021/4/30 5:03 下午
 * @Company:
 */
public class BIOserver {

    public static void main(String[] args) throws IOException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(8080);
        System.out.println("=============服务器启动成功");
        while (true) {
            Socket socket = serverSocket.accept();
            executorService.submit(new Runnable() {
                @SneakyThrows
                @Override
                public void run() {
                    handler(socket);
                }
            });
        }
    }

    public static void handler(Socket socket) throws IOException {
        try {
            InputStream in = socket.getInputStream();
            byte[] bytes = new byte[1024];
            while (true) {
                int cnt = in.read(bytes);
                if (cnt == -1) {
                    break;
                }
                String s = new String(bytes,0,cnt);
                System.out.println("接收到的数据:"+s);
            }
        }finally {
            System.out.println("关闭连接");
            socket.close();
        }

    }
}
